<?php

/**
* @copyright   (C) 2010 iJoomla, Inc. - All rights reserved.
* @license  GNU General Public License, version 2 (http://www.gnu.org/licenses/gpl-2.0.html) 
* @author  iJoomla.com webmaster@ijoomla.com
* @url   http://www.ijoomla.com/licensing/
* the PHP code portions are distributed under the GPL license. If not otherwise stated, all images, manuals, cascading style sheets, and included JavaScript  
* are NOT GPL, and are released under the IJOOMLA Proprietary Use License v1.0 
* More info at http://www.ijoomla.com/licensing/
*/

defined('_JEXEC') or die('Restricted access');
	
class QuestionMultipleAnswer{
	
	function QuestionMultipleAnswer(){
	}
	
	function display($orientation = "", $question_id, $survey_id, $params, $question_details, $completed, $session_id){
		$return = "";
		if($orientation == "vertical"){
			$return = $this->displayVertical($orientation = "", $question_id, $survey_id, $params, $question_details, $completed, $session_id);
		}
		elseif($orientation == "horizontal"){
			$return = $this->displayHorizontal($orientation = "", $question_id, $survey_id, $params, $question_details, $completed, $session_id);
		}
		return $return;		
	}
	
	function displayHorizontal($orientation = "", $question_id, $survey_id, $params, $question_details, $completed, $session_id){		
		$return_content_array = array();
		$return = "";
		$value = "";
		$question_class = isset($params->question)? $params->question : "";
		$question_description = isset($params->question_description)? $params->question_description : "";		
		$javascript = "";
		$value = "";
		$entered = "";
		$answers = $this->getAnswers($question_id);
		$validation = "";
		
		$return .= '<table width="100%" class="table_question">';
		$return .= 	  '<tr>';
		$return .= 	  	 '<td class="'.$question_class.'">';
		$return .=           $question_details["0"]["title"];
		if($question_details["0"]["required"] == "1"){
			$return .= '<span class="question_required"> *</span>';
			$javascript = ' onchange="setentertext(form.q'.$question_id.', this)" ';
			$validation = $this->createValidation($question_id, $question_details["0"]["title"]);					
		}
		$return .= 	  	 '</td>';
		$return .= 	  '</tr>';
		if($question_details["0"]["description"] != ""){
			$return .='<tr>';
			$return .= 	 '<td class="'.$question_description.'">';
			$return .=       $question_details["0"]["description"];
			$return .= 	 '</td>';
			$return .='</tr>';
		}
		$return .= 	  '<tr>';
		$return .= 	  	 '<td class="'.$question_class.'">';
		$return .= 	  	 	'<table width="100%">';
		$return .= 	  	 		'<tr>';
		if(count($answers)>0){
			$edit_values = $this->getValue1($question_id, $session_id);			
			foreach($answers as $key=>$value){				
				$checked = "";
				if(in_array($value["id"], $edit_values)){
					if(isset($completed["view_response"]) && $completed["view_response"]=="true"){
						$checked = ' checked="checked" ';
						$entered = $edit_values["0"];
					}
				}
				$return .= 	  	 	'<td>';
				$return .= 	  	 		'<input type="checkbox" '.$checked.' class="'.$params->checkbox.'" onchange="setentered(form.q'.$question_id.',this, &quot;question['.$question_id.'][answer_text]&quot;)" value="'.$value["id"].'" name="question['.$question_id.'][answer][]">
										<span class="'.$params->answer.'">'.$value["value"].'</span>';
				$return .= 	  	 	'</td>';			
			}	
		}
		$return .= 	  	 		'</tr>';		
		$return .= 	  	 		'<tr>';
		$return .= 	  	 			'<td>';
		$return .= 	  	 				'<input type="hidden" value="checkbox" name="question['.$question_id.'][type]">
										 <input type="hidden" value="'.$orientation.'" name="question['.$question_id.'][orientation]">';
		$return .= 	  	 			'</td>';
		$return .= 	  	 		'</tr>';
		$return .= 	  	 	'</table>';
		$return .= 	  	 '</td>';
		$return .= 	  '</tr>';
		$return .= '</table>';
		
		$return .= '<input type="hidden" id="q'.$question_id.'" name="q'.$question_id.'" value="'.$entered.'">';
		$return .= '<input type="hidden" id="qtext'.$question_id.'" name="qtext'.$question_id.'" value="">';
		$return .= '<input type="hidden" name="classes['.$question_id.']" value="QuestionMultipleAnswer">';		
		
		$return_content_array["content"] = $return;
		$return_content_array["validation"] = $validation;
		
		return $return_content_array;
	}
	
	function displayVertical($orientation = "", $question_id, $survey_id, $params, $question_details, $completed, $session_id){
		$return_content_array = array();
		$return = "";
		$value = "";
		$question_class = isset($params->question)? $params->question : "";
		$question_description = isset($params->question_description)? $params->question_description : "";		
		$javascript = "";
		$value = "";
		$entered = "";
		$answers = $this->getAnswers($question_id);
		$validation = "";
		
		$return .= '<table class="table_question">';
		$return .= 	  '<tr>';
		$return .= 	  	 '<td class="'.$question_class.'">';
		$return .=           $question_details["0"]["title"];
		if($question_details["0"]["required"] == "1"){
			$return .= '<span class="question_required"> *</span>';
			$javascript = ' onchange="setentertext(form.q'.$question_id.', this)" ';
			$validation = $this->createValidation($question_id, $question_details["0"]["title"]);					
		}
		$return .= 	  	 '</td>';
		$return .= 	  '</tr>';
		if($question_details["0"]["description"] != ""){
			$return .='<tr>';
			$return .= 	 '<td class="'.$question_description.'">';
			$return .=       $question_details["0"]["description"];
			$return .= 	 '</td>';
			$return .='</tr>';
		}
		$return .= 	  '<tr>';
		$return .= 	  	 '<td class="'.$question_class.'">';
		$return .= 	  	 	'<table>';
		if(count($answers)>0){
			$edit_values = $this->getValue1($question_id, $session_id);			
			foreach($answers as $key=>$value){
				$checked = "";
				if(isset($edit_values["0"]) && @in_array($value["id"], $edit_values)){
					if(isset($completed["view_response"]) && $completed["view_response"]=="true"){
						$checked = ' checked="checked" ';
						$entered = $edit_values["0"];
					}
				}	
				$return .= 	  	 '<tr>';
				$return .= 	  	 	'<td>';
				$return .= 	  	 		'<input type="checkbox" class="'.$params->checkbox.'" onchange="setentered(form.q'.$question_id.',this, &quot;question['.$question_id.'][answer_text]&quot;)" value="'.$value["id"].'" name="question['.$question_id.'][answer][]" '.$checked.'>
										<span class="'.$params->answer.'">'.$value["value"].'</span>';
				$return .= 	  	 	'</td>';
				$return .= 	  	 '</tr>';
			}	
		}
		if($question_details["0"]["other_field"] == "1"){
				$edit_values = $this->getValue2($question_id, $session_id);	
				$checked = "";
				if(trim($edit_values) != ""){
					$checked = ' checked="checked" ';
				}
				$return .= 	  	 '<tr>';
				$return .= 	  	 	'<td class="'.$params->answer.'">';
				$return .= 	  	 		'<input type="checkbox" class="'.$params->checkbox.'" name="question['.$question_id.'][answer][]" '.$checked.'>&nbsp;'.$question_details["0"]["other_field_title"].'&nbsp;:&nbsp;&nbsp;';
				$return .= 	  	 		'<input type="text" class="" onkeyup="setentertext(form.q'.$question_id.', this.value); if(this.value.length&gt;0) {change_checked(&quot;question['.$question_id.'][answer][]&quot;, '.count($answers).');} else {test_radios(q'.$question_id.',&quot;question['.$question_id.'][answer][]&quot;, '.count($answers).')}" value="'.$edit_values.'" name="question['.$question_id.'][answer_text]">';
				$return .= 	  	 	'</td>';
				$return .= 	  	 '</tr>';
		}
		$return .= 	  	 		'<tr>';
		$return .= 	  	 			'<td>';
		$return .= 	  	 				'<input type="hidden" value="checkbox" name="question['.$question_id.'][type]">
										 <input type="hidden" value="'.$orientation.'" name="question['.$question_id.'][orientation]">';
		$return .= 	  	 			'</td>';
		$return .= 	  	 		'</tr>';
		$return .= 	  	 	'</table>';
		$return .= 	  	 '</td>';
		$return .= 	  '</tr>';
		$return .= '</table>';
		
		$return .= '<input type="hidden" id="q'.$question_id.'" name="q'.$question_id.'" value="'.$entered.'">';
		$return .= '<input type="hidden" id="qtext'.$question_id.'" name="qtext'.$question_id.'" value="">';
		$return .= '<input type="hidden" name="classes['.$question_id.']" value="QuestionMultipleAnswer">';		
		
		$return_content_array["content"] = $return;
		$return_content_array["validation"] = $validation;
		
		return $return_content_array;
	}
	
	function getAnswers($question_id){
		$db =& JFactory::getDBO();		
		$query = $db->getQuery(true);
		$query->clear();		
		$query->select('id, value');
		$query->from('#__ijoomla_surveys_answers');
		$query->where("question_id=".intval($question_id));	
		$query->order("id asc");	
		$db->setQuery($query);		
		$db->query();
		$result = $db->loadAssocList();	
		return $result;
	}
	
	function createValidation($question_id, $title){
		$result = "";		
		$result .= '	if(document.survey_content.q'.$question_id.'.value==0 && document.survey_content.qtext'.$question_id.'.value==0){'."\n". 
				   '		alert(AlertText +"'.addslashes(trim($title)).'");'."\n".
				   '		return false;'."\n".
				   '	}';					   
		return $result;
	}
	
	function save($id, $type, $session_id){			
		$db =& JFactory::getDBO();
		
		$all_answers = JRequest::getVar("question");					
		$answers = @$all_answers[$id]["answer"];
							
		if($this->answerExist1($id, $session_id)){
			$sql = "delete from  #__ijoomla_surveys_result where q_id=".$id." and session_id=".$session_id;
			$db->setQuery($sql);
			$db->query();
		}
		if(isset($answers)){
			foreach($answers as $key=>$value){
				if(trim($value) != "on"){							
					$sql = "insert into #__ijoomla_surveys_result(`q_id`, `a_id`, `m_id`, `ac_id`, `session_id`, `value`) values (";					
					$sql .= $id.", ".$value.", 0, 0, ".$session_id.", 0";
					$sql .= ")";						
					$db->setQuery($sql);
					$db->query();
				}
			}
		}
		if($this->answerExist2($id, $session_id)){
			if(isset($all_answers[$id]["answer_text"]) && trim($all_answers[$id]["answer_text"]) != ""){
				$sql = "update #__ijoomla_surveys_result_text set `value`='".addslashes(trim($all_answers[$id]["answer_text"]))."' where `question_id`=".$id." and `session_id`=".$session_id;												
				$db->setQuery($sql);
				$db->query();
			}
			else{
				$sql = "delete from #__ijoomla_surveys_result_text where `question_id`=".$id." and `session_id`=".$session_id;												
				$db->setQuery($sql);
				$db->query();
			}
		}
		else{
			if(isset($all_answers[$id]["answer_text"]) && trim($all_answers[$id]["answer_text"]) != ""){
				$sql = "insert into #__ijoomla_surveys_result_text(`question_id`, `value`, `session_id`) values (";					
				$sql .= $id.", '".addslashes(trim($all_answers[$id]["answer_text"]))."', ".$session_id;
				$sql .= ")";												
				$db->setQuery($sql);
				$db->query();
			}
		}
	}
	
	function answerExist1($question_id, $session_id){
		$db =& JFactory::getDBO();
		$sql = "select count(*) from #__ijoomla_surveys_result where q_id=".$question_id." and session_id=".$session_id;
		$db->setQuery($sql);
		$db->query();
		$result = $db->loadResult();
		if($result != "0"){
			return true;
		}
		return false;
	}
	
	function answerExist2($question_id, $session_id){
		$db =& JFactory::getDBO();
		$sql = "select count(*) from #__ijoomla_surveys_result_text where question_id=".$question_id." and session_id=".$session_id;		
		$db->setQuery($sql);
		$db->query();
		$result = $db->loadResult();
		if($result != "0"){
			return true;
		}
		return false;
	}
	
	function getValue1($question_id, $session_id){
        if (!$session_id) { return NULL; }    
		$db =& JFactory::getDBO();		
		$query = $db->getQuery(true);
		$query->clear();		
		$query->select('a_id');
		$query->from('#__ijoomla_surveys_result');
		$query->where("q_id=".intval($question_id)." and session_id=".intval($session_id));		
		$db->setQuery($query);		
		$db->query();
		$result = $db->loadResultArray();				
		return $result;
	}
	
	function getValue2($question_id, $session_id){
        if (!$session_id) { return NULL; }    
		$db =& JFactory::getDBO();		
		$query = $db->getQuery(true);
		$query->clear();		
		$query->select('value');
		$query->from('#__ijoomla_surveys_result_text');
		$query->where("question_id=".intval($question_id)." and session_id=".intval($session_id));		
		$db->setQuery($query);		
		$db->query();
		$result = $db->loadResult();
		return $result;	
	}
	
	function editResult($id, $survey_id, $params, $i, $title, $all_responses_count){
		$answers = $this->getAnswers($id);
		$orientation = $this->getOrientation($id);
		$all_responses_count = $this->countPerQuestion($id, $orientation);		
		
		$return  = '<table width="100%" style="border:1px solid #CCCCCC; border-collapse:collapse;">';
		$return .= 		'<tr>';
		$return .= 			'<td class="'.$params->question.'" colspan="4" style="padding-left:5px;">';
		$return .= 				'<b>'.$i.". ".$title.'</b>';
		$return .= 			'</td>';
		$return .= 		'</tr>';
		$return .= 		'<tr>';
		$return .= 			'<td></td>';
		$return .= 			'<td></td>';
		$return .= 			'<td align="center">';
		$return .= 				JText::_("COM_SURVEYS_RESPONSE_PERCENT");
		$return .= 			'</td>';
		$return .= 			'<td align="center">';
		$return .= 				JText::_("COM_SURVEYS_TOTAL_RESPONSE");	
		$return .= 			'</td>';				
		$return .= 		'</tr>';
		$k = 0;
		$new_class = "";
		foreach($answers as $a_key=>$a_value){			
			$class = $params->table_row1;
			if($k%2 != 0){
				$new_class = $class;
				$class = $params->table_row2;				 
			}
			$k++;
			$count 	 = $this->countTotal1($a_value["id"]);			
			$return .= '<tr class="'.$class.'">';
			$return .= 		'<td align="right" style="padding-right:5px;">';			
			$return .= 			$a_value["value"];
			$return .= 		'</td>';			
			$return .= 		'<td align="left" width="30%">';
			if(intval($all_responses_count) != "0"){
				$return .= 		@$this->getPicture(number_format( (($count * 100) / $all_responses_count), 2, '.', '') );
			}
			$return .= 		'</td>';
			$return .= 		'<td align="center">';
			if(intval($all_responses_count) != "0"){
				$return .= 		@number_format( (($count * 100) / $all_responses_count), 2, '.', ''). " %";
			}
			$return .= 		'</td>';
			$return .= 		'<td align="center">';
			$return .= 			$count;
			$return .= 		'</td>';				
			$return .= '</tr>';	
		}
		$other_value = $this->getOtherValue($id);
		if($other_value != NULL && $other_value != "" && $orientation != "horizontal"){
			$count 	 = $this->countTotal2($id);
			$return .= 		'<tr class="'.$new_class.'">';
			$return .= 			'<td align="right" style="padding-right:5px;">';
			$return .= 				$other_value;
			$return .= 			'</td>';
			$return .= 			'<td align="left" width="30%">';
			if(intval($all_responses_count) != "0"){
				$return .= 				@$this->getPicture(number_format( (($count * 100) / $all_responses_count), 2, '.', '') );
			}
			$return .= 			'</td>';
			$return .= 			'<td align="center">';
			if(intval($all_responses_count) != "0"){
				$return .= 				@number_format( (($count * 100) / $all_responses_count), 2, '.', ''). " %";
			}
			$return .= 			'</td>';
			$return .= 			'<td align="center">';
			$controller = JRequest::getVar("controller", "", "get");
			$app =& JFactory::getApplication();
			if($count > 0){
				if($app->isAdmin()){
					if($controller != "" && $controller == "statistics"){
						$r_id = JRequest::getVar("r_id", "0");
						$link = JURI::root().'administrator/index.php?option=com_surveys&controller=editdetails&task=edit_details&q_id='.$id."&r_id=".$r_id;			
						$return .= '<a style="text-decoration:none;" href="'.$link.'">'.$count." ".JText::_("COM_SURVEYS_VIEW_DETAIL").'</a>'."&nbsp;&nbsp;";
					}				
				}
				else{
					$link = JRoute::_('index.php?option=com_surveys&controller=editsurvey&Itemid='.JRequest::getVar("Itemid").'&task=edit_details&q_id='.$id);
					$return .= '<a style="text-decoration:none;" href="'.$link.'">'.$count." ".JText::_("COM_SURVEYS_VIEW_DETAIL").'</a>'."&nbsp;&nbsp;";
				}
			}
			else{
				$return .= "0";
			}	
			$return .= 			'</td>';
			$return .= 		'</tr>';
		}
		$return .= 		'<tr>';
		$return .= 			'<td colspan="3" style="padding-right:5px;" align="right">';
		$return .= 				'<b>'.JText::_("COM_SURVEYS_TOTAL_RESPONDENTS").':</b>';
		$return .= 			'</td>';
		$return .= 			'<td class="'.$params->total_background.'" align="center">';
		$return .= 				'<b>'.$all_responses_count.'</b>';
		$return .= 			'</td>';
		$return .= 		'</tr>';		
		$return .= '</table>';
		return $return;		
	}
	
	function countTotal1($a_id){
		$r_id = JRequest::getVar("r_id", "");
		$and = "";
		if($r_id != ""){
			$and = " and session_id=".$r_id;
		}
		$db =& JFactory::getDBO();		
		$sql = "select count(*) from #__ijoomla_surveys_result where a_id=".$a_id.$and;				
		$db->setQuery($sql);
		$db->query();
		$result = $db->loadResult();
		return $result;
	}
	
	function countTotal2($id){
		$r_id = JRequest::getVar("r_id", "");
		$and = "";
		if($r_id != ""){
			$and = " and session_id=".$r_id;
		}
		$db =& JFactory::getDBO();		
		$sql = "select count(*) from #__ijoomla_surveys_result_text where question_id=".$id.$and;				
		$db->setQuery($sql);
		$db->query();
		$result = $db->loadResult();			
		return $result;
	}
	
	function countPerQuestion($id, $orientation){		
		$r_id = JRequest::getVar("r_id", "");
		$and = "";
		if($r_id != ""){
			$and = " and session_id=".$r_id;
		}
		$db =& JFactory::getDBO();		
		$sql = "select count(*) from #__ijoomla_surveys_result where q_id=".$id.$and;
		$db->setQuery($sql);
		$db->query();
		$result1 = $db->loadResult();
		if($orientation != "horizontal"){
			$sql = "select count(*) from #__ijoomla_surveys_result_text where question_id=".$id;				
			$db->setQuery($sql);
			$db->query();
			$result2 = $db->loadResult();
			return $result1+$result2;
		}
		else{
			return $result1;
		}				
	}
	
	function getPicture($value){	
	    $picture = "";
		$picture .= "<div style=\"width:100%;\">";
		$picture .= 	"<div style=\"width:" . $value . "%; background-color:#0000CC;\"> &nbsp; ";
		$picture .= 	"</div>";
		$picture .= "</div>";
		return $picture;
	}
	
	function getOtherValue($id){
		$db =& JFactory::getDBO();		
		$sql = "select other_field_title from #__ijoomla_surveys_questions where id=".$id;				
		$db->setQuery($sql);
		$db->query();
		$result = $db->loadResult();			
		return $result;
	}
	
	function getOrientation($id){
		$db =& JFactory::getDBO();		
		$sql = "select orientation from #__ijoomla_surveys_questions where id=".$id;				
		$db->setQuery($sql);
		$db->query();
		$result = $db->loadResult();			
		return $result;
	}
	
	function getForHeader($id, $title){		
		return $title;
	}
	
	function getForRow($q_id, $sess_id){
		$result_array = array();
		$db =& JFactory::getDBO();		
		$sql = "select a.value from #__ijoomla_surveys_answers a, #__ijoomla_surveys_result r where a.question_id=".$q_id." and a.id=r.a_id and r.session_id=".$sess_id;				
		$db->setQuery($sql);
		$db->query();
		$result = $db->loadAssocList();
		
		if($result != NULL && is_array($result) && count($result)>0){
			foreach($result as $key=>$value){								
				if(isset($value["value"]) && trim($value["value"]) != ""){
					$result_array[] = trim($value["value"]);
				}
			}
		}
		
		$sql = "select rt.value from #__ijoomla_surveys_answers a, #__ijoomla_surveys_result_text rt where rt.question_id=".$q_id." and rt.session_id=".$sess_id;				
		$db->setQuery($sql);
		$db->query();
		$result = $db->loadResult();
		if($result != NULL && trim($result) != ""){
			$result_array[] = trim($result);
		}		
		if(count($result_array) > 0){
			return implode(" AND ", $result_array);
		}
		else{
			return "NO ANSWER";
		}				
	}
	
	function getQuestionResultForEmail($q_id, $session_id, $title){		
		$return = $title.":"."\n";
		
		$db =& JFactory::getDBO();		
		$sql = "select a.value from #__ijoomla_surveys_answers a, #__ijoomla_surveys_result r where a.question_id=".$q_id." and a.id=r.a_id and r.session_id=".$session_id;				
		$db->setQuery($sql);
		$db->query();
		$result = $db->loadAssocList();
		
		if($result != NULL && is_array($result) && count($result)>0){
			foreach($result as $key=>$value){								
				if(isset($value["value"]) && trim($value["value"]) != ""){
					$return .= "\t".trim($value["value"])."\n";
				}
			}
		}
		
		$sql = "select rt.value from #__ijoomla_surveys_answers a, #__ijoomla_surveys_result_text rt where rt.question_id=".$q_id." and rt.session_id=".$session_id;				
		$db->setQuery($sql);
		$db->query();
		$result = $db->loadResult();
		if($result != NULL && trim($result) != ""){
			$return .= "\t".trim($result);
		}		
		return $return;				
	}	
	
	function checkCompleted($logic, $compare, $answer, $skip_answer){
		$return = false;
		
		if($logic == "OR"){
			if($compare == "equal"){
				foreach($skip_answer as $key=>$value){
					if(in_array($value, $answer)){
						$return = true;
						return $return;
					}
				}
			}
			elseif($compare == "different"){
				foreach($skip_answer as $key=>$value){
					if(in_array($value, $answer)){
						$return = false;
						return $return;
					}
				}
				$return = true;
				return $return;
			}
		}
		elseif($logic == "AND"){
			if($compare == "equal"){
				foreach($skip_answer as $key=>$value){
					if(!in_array($value, $answer)){
						$return = false;
						return $return;
					}
				}
				$return = true;
				return $return;
			}
			elseif($compare == "different"){
				foreach($answer as $key=>$value){
					if(in_array($value, $skip_answer)){
						$return = false;
						return $return;						
					}
				}
				$return = true;
				return $return;
			}
		}			
	}
			
};

?>